<?php

defined('SYSPATH') or die('Access error!');

class Controller_Order extends Controller_Shop_Main
{

    private $order;

    public function before()
    {
        parent::before();
        $this->order = Model::factory('shop_order');
        I18n::set_current_file('shop');

        if (!$this->logged_in())
        {
            Message::error('请先登录');
            $this->request->redirect(Route::get('user')->uri(array('action' => 'login')));
        }
        if (isset($_POST['_token']) && !CSRF::check_csrf_token($_POST['_token']))
        {
            $this->request->redirect(URL::site('csrf/index'));
        }
    }

    public function action_submit()
    {
        $goods_id = intval(Arr::get($_POST, 'goods_id'));
        if (empty($goods_id))
        {
            $this->request->redirect(Route::get('shop')->uri(array('action' => 'index')));
        }
        $goods_info = Model::factory('shop_goods')->get_goods_detail($goods_id);
        $order_info = $this->handle_order_info($goods_info);

        $order_id = $this->order->insert($order_info);
        if ($order_id)
        {
            //添加产品
            Model::factory('shop_order_goods')->insert($this->handle_goods_info($order_id, $goods_info));
            //更改订单日志
            Model::factory('shop_order_log')->insert($this->handle_log_info($order_id, SHOP_ORDER_SUBMITTED, SHOP_ORDER_UNPAY));
            Message::success(__('order submit'));
        }
        $message = '';
        if (!Model::factory('user_account')->checke_user_account($goods_info['account'], $goods_info['account_type']))
        {
            $message = $this->get_submit_message($goods_info['account_type']);
        }
        $this->template->assign('data', $goods_info);
        $this->template->assign('order_id', $order_id);
        $this->template->assign('order_message', $message);
        $this->template->assign('_token',  CSRF::set_csrf_token());
        $this->template->view('shop_order_submit');
    }

    public function action_pay()
    {
       $id = intval(Arr::get($_POST, 'order_id'));
        if (empty($id))
        {
            $this->request->redirect(Route::get('shop')->uri(array('action' => 'index')));
        }

        //获取订单的资料
        $order_detail = $this->order->get_row(array('id' => $id), 'order_account,account_type');
        //判断订单是否存在
        if (!Arr::validate_arr($order_detail) > 0)
        {
            Message::error('订单不存在');
            $this->request->redirect(Route::get('shop')->uri(array('action' => 'index')));
        }
        $pay_message = '支付失败';
        //处理用户的资金
        if ($this->handle_pay_account($this->user_detail['id'], $order_detail['account_type'], $order_detail['order_account'], $id))
        {
            $data = array();
            $data['status'] = SHOP_ORDER_PAYED;
            $data['pay_time'] = Date::get_time();
            //更改订单状态
            if ($this->order->update($data, array('id' => $id)))
            {
                //更改订单日志
                Model::factory('shop_order_log')->insert($this->handle_log_info($id, SHOP_ORDER_UNPAY, SHOP_ORDER_PAYED));
            }
            $pay_message = '支付成功';
        }

        $this->template->assign('pay_message', $pay_message);
        $this->template->view('shop_order_pay');
    }

    //处理订单的信息
    public function handle_order_info($goods_info)
    {
        $order_status = SHOP_ORDER_UNPAY;
        /* 返回基本信息 */
        return array(
            'order_sn' => $this->create_order_sn(),
            'seller_userid' => $goods_info['user_id'],
            'seller_name' => $goods_info['username'],
            'buyer_userid' => $this->user_detail['id'],
            'buyer_name' => $this->user_detail['username'],
            'buyer_email' => $this->user_detail['email'],
            'status' => $order_status,
            'add_time' => Date::get_time(),
            'goods_account' => $goods_info['account'],
            'order_account' => $goods_info['account'],
            'account_type' => $goods_info['account_type'],
        );
    }

    public function handle_goods_info($order_id, $goods_info)
    {
        return array(
            'order_id' => $order_id,
            'goods_id' => $goods_info['id'],
            'goods_name' => $goods_info['name'],
            'account' => $goods_info['account'],
            'quantity' => 1,
            'goods_image' => $goods_info['goods_image'],
        );
    }

    public function handle_log_info($order_id, $now_status, $change_status)
    {
        return array(
            'order_id' => $order_id,
            'operator' => $this->user_detail['username'],
            'order_status' => $now_status,
            'changed_status' => $change_status,
            'log_time' => Date::get_time(),
        );
    }

    //生成单号
    public function create_order_sn()
    {
        mt_srand((double) microtime() * 1000000);
        $timestamp = Date::get_time();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = 'jsw'.$y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        //查看是否重复 
        if ($this->order->get_var(array('order_sn' => $order_sn), 'id'))
        {
            return $this->create_order_sn();
        }
        return $order_sn;
    }

    public function get_submit_message($account_type)
    {
        switch ($account_type)
        {
            case 'points':
                return '用户的积分不足以支付该产品';
                break;
            case 'amount':
                return '用户的钱不足以支付该产品';
                break;
            default:
                break;
        }
    }

    public function handle_pay_account($user_id, $account_type, $account, $order_id)
    {
        switch ($account_type)
        {
            case 'points':
                return Model_User_Points::factory('user_points')->save_points($user_id, array('order_buy_goods' => $account), $order_id);
                break;
            default:
                break;
        }
    }

}